package bscripts.btoolkit.network {

	import laya.net.HttpRequest;
	import laya.events.Event;
	
	public class Http {
		/**
		 * 跨域访问：服务器配置：在response里添加
		 * response.setHeader("Access-Control-Allow-Origin", "*"); 
		 */

		public static function get(url: String, succeedCallback: Function, errorCallback: Function = null, isResponseJson: Boolean = false): void {
			var request:HttpRequest = new HttpRequest();
			request.on(Event.COMPLETE, Http, function(e:Object):void{
				succeedCallback(JSON.stringify(e));
			});
			request.on(Event.ERROR, Http, function(e: Object):void{
				console.error("IOError(" + url + "): " + JSON.stringify(e));
				if (errorCallback != null) {
					errorCallback();
				}
			});
			request.send(url, "", "get", isResponseJson ? "json" : "text");
		}

		public static function post(url: String, params: Object, succeedCallback: Function, errorCallback: Function = null, isRequestJson: Boolean = false, isResponseJson: Boolean = false): void {
			var request:HttpRequest = new HttpRequest();
			request.once(Event.COMPLETE, Http, function(e:Object):void {
				succeedCallback(JSON.stringify(e));
			});
			request.once(Event.ERROR, Http, function(e:Object):void {
				console.error("IOError(" + url + "): " + JSON.stringify(e));
				if (errorCallback != null) {
					errorCallback();
				}
			});
			var headers:Array = null;
			if (isRequestJson) {
				headers = ["Content-Type", "application/json"];
			} else {
				headers = ["Content-Type", "application/x-www-form-urlencoded"];
			}
			var paramsStr:String = "";
			if (isRequestJson) {
				paramsStr = JSON.stringify(params);
			} else {
				for (var key:String in params) {
					if (paramsStr == '') {
						paramsStr += key + "=" + params[key];
					} else {
						paramsStr += "&" + key + "=" + params[key];
					}
				}
			}
			request.send(url, paramsStr, "post", isResponseJson ? "json" : "text", headers);
		}

		public static function getParamFromUrl(key: String): String {
			var url:String = __JS__('window.document.location.href.toString()');
			var u:* = url.split("?");
			if (u[1] is String)
			{
				u = u[1].split("&");
				var gets:Object = {};
				for (var i:String in u)
				{
					var j:String = u[i].split("=");
					gets[j[0]] = j[1];
				}
				return gets[key];
			}
			return null;
		}
	}
}